package cn.edu.tju.core.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件上传配置类
 * 配置上传文件的存储位置和访问路径
 */
@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
    
    // 从配置文件中获取上传目录的路径
    @Value("${file.upload-dir:${user.dir}/uploads}")
    private String uploadDir;
    
    /**
     * 业务图片上传目录
     */
    @Value("${file.business-upload-dir:${file.upload-dir}/business}")
    private String businessUploadDir;
    
    /**
     * 食品图片上传目录
     */
    @Value("${file.food-upload-dir:${file.upload-dir}/food}")
    private String foodUploadDir;
    
    /**
     * 配置静态资源的访问路径
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 将上传的文件目录映射到URL路径
        Path uploadPath = Paths.get(uploadDir);
        String uploadAbsolutePath = uploadPath.toFile().getAbsolutePath();
        
        // 配置上传文件的访问路径
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadAbsolutePath + "/");
    }
    
    /**
     * 获取业务图片上传目录
     */
    public String getBusinessUploadDir() {
        return businessUploadDir;
    }
    
    /**
     * 获取食品图片上传目录
     */
    public String getFoodUploadDir() {
        return foodUploadDir;
    }
    
    /**
     * 获取上传文件的URL前缀
     */
    public String getUploadUrlPrefix() {
        return "/uploads/";
    }
    
    /**
     * 获取业务图片的URL前缀
     */
    public String getBusinessImageUrlPrefix() {
        return getUploadUrlPrefix() + "business/";
    }
    
    /**
     * 获取食品图片的URL前缀
     */
    public String getFoodImageUrlPrefix() {
        return getUploadUrlPrefix() + "food/";
    }
} 